#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys
from optparse import OptionParser
from plane import Plane
from grid_plane import PlaneGrid

def readdensity(fname):
    f = open(fname, 'r')	
    lines = f.readlines(); f.close
    result = []
    size = int(float(lines.pop(0)))
    max_density_val = float(lines.pop(0))
    for line in lines:
        valyes = [float(x) for x in line.split()]
        result.append(valyes)
    return result, size, max_density_val

def f (dip):
    return (90-dip)*4.0    

optparser= OptionParser()   
optparser.add_option('-d', dest='dfile',
					help='Plot the density grid, which store in the file name, on the background')
optparser.add_option('-s', '--sigma', dest='sigma',
                     help='size of a net cell',
                     default=5)					
optparser.add_option('-b', dest='belt',
                     help='Makes output for belt drawing',
                     action='store_true',
                     default=False)                     
optparser.add_option('-i', dest='intens',
                     help='Makes output with intensity value',
                     action='store_true',
                     default=False)                     
options, args = optparser.parse_args(sys.argv[1:])
density, size, max_density_val = None, None, None
if options.dfile:
	density, size, max_density_val = readdensity(options.dfile)

sigma=float(options.sigma)

# prepare grid for searching max
grid = PlaneGrid(incr=[int(size), int(size)])
for pl in density:        
    grid.add(plane=Plane(pl[0], pl[1]), val=pl[2])
density_grid = grid.returnGrid()						

# searching max
maxs = []
time = (360.0/size)*(90/size) # for doing elapsing time 
i = 0.0
for cdir in range(0,360, size):    
    for cdip in range(0, 90, size):
        # perfoming some useful information on elapsing time
        sys.stderr.write('%.4f\r' % (i/time)) 
        i += 1
        
        cmax = []
        cell = Plane(cdir, cdip)
        cval = grid.get(plane = cell)
        if cval<.03:
            continue
        for odir in range(0,360,size):
            for odip in range(0,90,size):
                other = Plane(odir, odip)
                oval = grid.get(plane=other)
                angle = cell.normal().return_angle_between(other.normal())
                if angle<2*sigma or abs(180-angle)<2*sigma :                
                    cmax.append(not(cval < oval))         
        if False not in cmax:
            maxs.append([cell, cval])
# searching doubling entries
i = 0
while i < len(maxs):
    cplane = Plane(maxs[i][0].dir, maxs[i][0].dip)
    for pl in maxs:
        oplane = Plane(pl[0].dir, pl[0].dip)
        if cplane.dir==oplane.dir and cplane.dip==oplane.dip: continue
        if cplane.return_angle_between(oplane) < .5*sigma:
            maxs.pop(i)
    i+=1

# genereting report
if options.belt:
    mval=0.0
    # searchin maximum value
    for pl in maxs:
        mval = max([mval, pl[1]])
    for pl in maxs:
        sys.stdout.write('%003d %02d l %0.1f,%0.1f,%0.1f\n' % (pl[0].dir, pl[0].dip, 1-pl[1]/mval, 1-pl[1]/mval, 1-pl[1]/mval))          
elif options.intens:
    for pl in maxs:
        sys.stdout.write('%003d %02d %0.1f\n' % (pl[0].dir, pl[0].dip, pl[1]))          
else:
    for pl in maxs:
        sys.stdout.write('%003d %02d\n' % (pl[0].dir, pl[0].dip))          
        sys.stderr.write('%003d %02d %g\n' % (pl[0].dir, pl[0].dip, pl[1]))          
